﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Project.Core.Config.Common.Lang;

namespace Project.Core.Config.Controllers {
    /// <summary>
    /// 异常信息控制器
    /// </summary>
    [ApiController]
    public class ErrorController : ControllerBase {

        /// <summary>
        /// 注入ASP.NET Core ILogger服务。
        /// 将控制器类型指定为泛型参数。
        /// 这有助于我们进行确定哪个类或控制器产生了异常，然后记录它
        /// </summary>
        public ILogger<ErrorController> Logger { get; set; }

        /// <summary>
        /// 异常状态码处理
        /// </summary>
        /// <param name="statusCode">状态码</param>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        [AllowAnonymous]
        [Route("Error/{statusCode}")]
        [ApiExplorerSettings(IgnoreApi = true)]
        public Result HttpStatusCodeHandler(int statusCode) {

            var statusCodeResult = HttpContext.Features.Get<IStatusCodeReExecuteFeature>();
            /*
             * OriginalPath：获取原始请求的路径。
             * OriginalQueryString：获取原始请求的查询参数字符串。
             * OriginalPathBase：获取原始请求的路径基础路径。
             * OriginalMethod：获取原始请求的 HTTP 方法。
             * OriginalHeaders：获取原始请求的 HTTP 头部。
             * OriginalBody：获取原始请求的请求体。
             * **/
            string msg = "访问失败";

            switch (statusCode) {
                case 401:
                    msg = "请先登录";
                    break;
                case 403:
                    msg = "没有权限访问";
                    break;
                case 404:
                    msg = "NotFound";
                    break;
                case 405:
                    msg = "Method Not Allowed";
                    break;
            }
            Logger.LogError($"发生了一个{statusCode}错误。路径：{statusCodeResult.OriginalPath}。以及查询字符串：{statusCodeResult.OriginalQueryString}");
            return Result.Fail(statusCode, msg, "");
        }

        /// <summary>
        /// 异常处理
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        [AllowAnonymous]
        [Route("Error")]
        [ApiExplorerSettings(IgnoreApi = true)]
        public Result Error() {
            var exceptionHandlerPathFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();

            Logger.LogError($"路径：{exceptionHandlerPathFeature.Path}，产生了一个错误：{exceptionHandlerPathFeature.Error}");
            //ViewBag.ExceptionPath = exceptionHandlerPathFeature.Path;
            //ViewBag.ExceptionMessage = exceptionHandlerPathFeature.Error.Message;
            //ViewBag.StackTrace = exceptionHandlerPathFeature.Error.StackTrace;
            return Result.Fail("Error");
        }
    }
}
